import General from '@/api/general'
import { formatTimes, imageCompress } from '@/libs/tool'
import mapPlugin from '@/libs/mapPlugin'
export default {
  data() {
    return {
      formattedAddress: '',
      previewImage: false
    }
  },
  methods: {
    // 文件上传之前
    uploadBeforeRead(file) {
      // 除了图片上传之外的文件校验
      if (file.type.indexOf('image') === -1 && file.size > this.maxSize) {
        this.$toast.fail(`文件过大，文件大小不能超过${this.maxSize / (1024 * 1024)}M`)
        return false
      } else {
        return true
      }
    },
    // 文件上传
    async uploadAfterRead({ file }, detail) {
      this.$toast.loading({
        message: '加载中...',
        duration: 0,
        overlay: true
      })
      // 事件中心 - 已到达拍照加水印
      if (detail.name === 'arriveFileList') {
        const _this = this
        mapPlugin.geolocation(result1 => {
          mapPlugin.geocoder(
            result1.position,
            async result2 => {
              _this.formattedAddress = result2.regeocode.formattedAddress
              file = await this.setWatermark(file)
              this.uploadFile(file, detail)
            },
            () => {
              _this.$toast.clear()
            }
          )
        })
      } else {
        this.uploadFile(file, detail)
      }
    },
    async uploadFile(file, detail) {
      // 上传路径
      let folder = ''
      if (file.type.indexOf('image') > -1) {
        // 身份证路径与图片路径区分
        if (detail.name === 'idCardFileList') {
          folder = this.idCardFolder
        } else {
          folder = `${this.folder}/img`
        }
        // 图片压缩
        file = await this.imgCompress(file)
      } else if (file.type.indexOf('video') > -1) {
        folder = `${this.folder}/video`
      } else if (file.type.indexOf('application') > -1) {
        folder = `${this.folder}/file`
      }
      const formData = new FormData()
      formData.append('folder', folder)
      formData.append('file', file)
      General.ImgUpload.upload(formData)
        .then(res => {
          this.$toast.clear()
          const { data, status } = res.data
          if (status === 0) {
            this[detail.name][detail.index].url = data
            // 解决视频上传完成之后回显的问题
            file.url = data
            this.previewImage = false
            this.$nextTick(() => {
              this.previewImage = true
            })
            this.uploadAfter(detail)
          } else {
            this[detail.name].splice(detail.index, 1)
            this.$toast.fail(res.data.message)
          }
        })
        .catch(() => {
          this.$toast.clear()
        })
    },
    // 上传成功之后处理
    uploadAfter(detail) {},
    setWatermark(file) {
      return new Promise(resolve => {
        const fileName = file.name
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          const date = formatTimes.formatTime(new Date())
          this.formattedAddress &&
            this.getImgUrl({
              url: reader.result,
              content: this.formattedAddress + '###' + date,
              cb: base64 => {
                const file = this.base64ToFile(base64, fileName)
                resolve(file)
              }
            })
        }
      })
    },
    base64ToFile(urlData, fileName) {
      const arr = urlData.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bytes = atob(arr[1]) // 解码base64
      let n = bytes.length
      const ia = new Uint8Array(n)
      while (n--) {
        ia[n] = bytes.charCodeAt(n)
      }
      return new File([ia], fileName, { type: mime })
    },
    // 水印
    getImgUrl({
      url = '',
      textAlign = 'end',
      textBaseline = 'bottom',
      fillStyle = 'rgba(255, 255, 255, 1)',
      content = '我是水印哈哈哈',
      font = '100px Arial',
      cb = null,
      textX = 100,
      textY = 70
    }) {
      const img = new Image()
      img.src = url
      img.crossOrigin = 'anonymous'
      img.onload = function () {
        const canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0)
        ctx.textAlign = textAlign
        ctx.textBaseline = textBaseline
        ctx.font = font
        ctx.fillStyle = fillStyle
        ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'
        ctx.shadowOffsetX = 2
        ctx.shadowOffsetY = 2
        let font_ = ''
        if (img.width * img.height > 2000000 && img.width * img.height < 4000000) {
          font_ = 80
        } else if (img.width * img.height > 4000000) {
          font_ = 120
        } else {
          font_ = 30
        }
        ctx.font = font_ + 'px Arial'
        // ctx.translate((img.width + textX) / 2, (img.height + textY) / 2)
        // ctx.rotate((Math.PI / 180) * -30)
        // ctx.translate(-(img.width + textX) / 2, -(img.height + textY) / 2)
        // 单独绘制水印
        const contentArr = content.split('###')
        for (let i = 0; i < contentArr.length; i++) {
          ctx.fillText(contentArr[i], img.width - font_, img.height - font_ * (i + 1))
        }
        // 循环绘制水印
        // for (let i = 0; i < img.height / 120; i++) {
        //   for (let j = 0; j < img.width / 30; j++) {
        //     ctx.fillText(content, i * 200, j * 100, img.width)
        //   }
        // }
        // 将绘制完成的canvas转换为base64的地址
        const base64Url = canvas.toDataURL()
        // return base64Url
        cb && cb(base64Url)
      }
    },
    // 图片压缩
    imgCompress(file) {
      return new Promise((resolve, reject) => {
        // 创建一个reader
        // 将图片2将转成 base64 格式
        const reader = new FileReader()
        // 读取成功后的回调
        reader.readAsDataURL(file)
        reader.onloadend = function () {
          const img = new Image()
          img.src = this.result
          if (this.result.length <= 1024 * 1024) {
            resolve(file)
          } else {
            img.onload = function () {
              const data = imageCompress.compress(img)
              resolve(imageCompress.dataURLtoFile(data, file.name))
            }
          }
        }
      })
    }
  }
}
